const axios = require('axios');
const util = require('../utils/util.js');
const cheerio = require('cheerio');
const details = require('./details');

const GetList = async () => {
	const conf = await util.ReadConfigFile('pages');
	const list = [];
	for (let i = conf.selfPages; i <= conf.totalPages; i++) {
		const url = `https://www.dkewl.com/code/page_${i}.html`;
		const resp = await axios.get(url);
		conf.selfPages = i;
		await util.WriteConfigFile('pages', conf)
		const $ = cheerio.load(resp.data);
		const listDom = $('.fly-case-list li');

		listDom.each((index, element) => {
			const listItem = $(element);
			const link = listItem.find('.fly-case-img').attr('href');
			// 如果 imgLink 存在，将其添加到列表中
			if (link) {
				list.push(link);
			}
			console.log('link', link)
		});
	}
	await util.WriteConfigFile('list', list)

	console.log('List of href attributes:', list);
};
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

const GetListDetails = async () => {
	try {
		const list = await util.ReadConfigFile('list');
		console.log('list', list);

		for (const item of list) {
			console.log('item', item)
			await details.GetDetails(item);
			let writeList = await util.ReadConfigFile('list');
			writeList.shift();
			await util.WriteConfigFile('list', writeList)
			
			await sleep(30000); // 等待一分钟
		}

	} catch (error) {
		console.error('Error:', error);
	}
};

module.exports = {
	GetList,
	GetListDetails
};
